/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.weso.acota.dao;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.traversal.NodeIterator;
import org.weso.acota.to.RequestSuggestionTO;
import org.weso.acota.to.SuggestionTO;
import org.weso.acota.to.TagTO;
import org.weso.acota.utils.DocumentBuilderHelper;

/**
 *
 * @author chema
 */
public class YQLSuggestDAOImpl implements SuggestDAO {

    private String yqlUrl = "http://query.yahooapis.com/v1/public/yql?q=";

    private String query = "select * from search.suggest where query=";

            
    public SuggestionTO suggest(RequestSuggestionTO request) {
        NodeIterator it;
        try {
            URL url = new URL(this.yqlUrl +
                    URLEncoder.encode(this.query+"\""+ request.getWord()+"\"", "UTF-8"));

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Accept", "application/xml");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK
                     && connection.getContentType().contains("text/xml")) {
               InputStream is = connection.getInputStream();
                //XML
              
                //Configuring XPATH with JAXEN AND DOM4J
                /*
                SuggestionTO suggestion = new SuggestionTO();
                SAXReader reader = new SAXReader();
                org.dom4j.Document document = reader.read(is);
                Map map = new HashMap();
                map.put( "ns1", "urn:yahoo:srch");
                Dom4jXPath xpath = new Dom4jXPath( "//text()");
               // xpath.setNamespaceContext( new SimpleNamespaceContext( map));
                List<TagTO> tags = new LinkedList<TagTO>();
                it = xpath.selectNodes(document).iterator();
 */
                Document result = DocumentBuilderHelper.getDocumentFromInputStream(is);
                it = org.apache.xpath.XPathAPI.selectNodeIterator(result, "//text()");
               
                SuggestionTO suggestion = new SuggestionTO();
                List<TagTO> tags = new LinkedList<TagTO>();
                 Node n = it.nextNode();
                while(n != null){
                    tags.add(new TagTO(YQLSuggestDAOImpl.class.getSimpleName(),n.getTextContent()));
                    n = it.nextNode();
                }
                suggestion.setTags(tags);
                return suggestion;
            } else {
                throw new RuntimeException("Unable to get a representation of the resource");
            }
        } catch (Exception e) {

            throw new RuntimeException(e);
        }
    }
}
